package com.gitee.huanminabc.jcommon.file;

import com.gitee.huanminabc.jcommon.exception.CommonException;
import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.nio.file.Files;

/**
 * 简要描述
 *
 * @Author: mac
 * @Date: 2025/4/3 13:42
 * @Version: 1.0
 * @Description: 文件作用详细描述....
 */
@Slf4j
public class FileWriterUtil {
    /**
     * 将字符串写入文本中,(覆盖方式)
     *
     * @param path 写入的文件
     * @param str  需要追加的字符串
     */
    public static void writerStrToFile(String str, File path ) {
        writerStrToFile( str,path, false);
    }

    private static void writerStrToFile(String str, File path, boolean append) {
        try (BufferedWriter bw =
                     new BufferedWriter(new OutputStreamWriter(new FileOutputStream(path, append)));) {
            bw.write(str);
        } catch (Exception e) {
            throw new CommonException(e);
        }
    }

    //将全部字节写入到文件中
    public static void writeByteToFile(byte[] b, File writePath, boolean append) {
        try (
                FileOutputStream fos1 = new FileOutputStream(writePath, append);
                BufferedOutputStream fos = new BufferedOutputStream(fos1);) {
            fos.write(b, 0, b.length); // 写入数据
        } catch (IOException e) {
            throw new CommonException(e);
        }
    }

    //将全部字节写入到文件中,(覆盖方式)
    public static void writeByteToFile(byte[] b, File writePath) {
        writeByteToFile(b, writePath, false);
    }


    //将InputStream写入到文件中
    public static void writeInputStreamToFile(InputStream inputStream, File file) {
        try (BufferedInputStream bis = new BufferedInputStream(inputStream);
             BufferedOutputStream bos = new BufferedOutputStream(Files.newOutputStream(file.toPath()));) {
            byte[] data = new byte[4096];
            int len;
            while ((len = bis.read(data)) != -1) {
                bos.write(data, 0, len); // 写入数据
            }
        } catch (IOException e) {
            throw new CommonException(e);
        }
    }
    public static void writeByteToOutputStream(final byte[] data, final OutputStream output){
        try {
            output.write(data);
        } catch (IOException e) {
            throw new CommonException(e);
        } finally {
            try {
                output.close();
            } catch (IOException e) {
                log.error("关闭输出流失败", e);
            }
        }
    }
}
